# email_sender.py
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import threading
from datetime import datetime
from config import load_config
# 发件人邮箱配置
smtp_server = 'smtp.qq.com'  # QQ邮箱SMTP服务器
smtp_port = 465  # SSL端口
my_sender = '931659829@qq.com'  # 发件邮箱地址
my_pass = 'ifufltdugxumbcea'  # SMTP授权码
# my_user = '2749419336@qq.com'  # 接收提醒的邮箱地址

def send_alert_email(alert_type="陌生人检测", location="门口", additional_info=""):
    """
    发送智能门神预警邮件
    
    参数:
    alert_type: 警报类型 (默认: "陌生人检测")
    location: 检测位置 (默认: "门口")
    additional_info: 附加信息
    """
    # 从配置中获取目标邮箱
    config = load_config()
    my_user = config.get('target_email')  # 默认值作为后备
    # 获取当前时间
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 构建邮件主题
    subject = f"【智能门神】{alert_type}警报 - {current_time}"
    
    # 构建邮件内容
    email_content = f"""
    <html>
    <body>
        <h2>🚨 智能门神系统警报</h2>
        <p>您的智能门神系统检测到异常情况，请及时关注：</p>
        
        <table border="0" cellpadding="5">
        <tr><td><b>警报类型：</b></td><td>{alert_type}</td></tr>
        <tr><td><b>发生位置：</b></td><td>{location}</td></tr>
        <tr><td><b>发生时间：</b></td><td>{current_time}</td></tr>
        </table>
        
        <p><b>系统已采取的措施：</b></p>
        <ul>
            <li>已自动开启录像功能</li>
            <li>已保存相关视频证据</li>
        </ul>
        
        {f'<p><b>附加信息：</b><br/>{additional_info}</p>' if additional_info else ''}
        
        <p><b>建议操作：</b></p>
        <ol>
            <li>如为访客，请忽略</li>
            <li>如情况可疑，请及时处理或报警</li>
        </ol>
        
        <hr>
        <p style="color: gray; font-size: 12px;">
            此邮件由智能门神系统自动发送，请勿直接回复。<br>
            如非您本人操作，请忽略此邮件。
        </p>
    </body>
    </html>
    """
    
    try:
        # 创建邮件内容 (使用HTML格式)
        msg = MIMEText(email_content, 'html', 'utf-8')
        msg['From'] = formataddr(["智能门神系统", my_sender])
        msg['To'] = formataddr(["主人", my_user])
        msg['Subject'] = Header(subject, 'utf-8')
        
        # 建立SSL安全连接
        server = smtplib.SMTP_SSL(smtp_server, smtp_port)
        server.login(my_sender, my_pass)
        server.sendmail(my_sender, [my_user], msg.as_string())
        server.quit()
        
        print(f"[{current_time}] 预警邮件发送成功: {alert_type}")
        return True
        
    except Exception as e:
        print(f"[{current_time}] 发送邮件时出错: {e}")
        return False

def send_alert_async(alert_type="陌生人检测", location="门口", additional_info=""):
    """
    异步发送预警邮件（避免阻塞主线程）
    """
    thread = threading.Thread(
        target=send_alert_email,
        args=(alert_type, location, additional_info)
    )
    thread.daemon = True
    thread.start()

# 测试函数
if __name__ == "__main__":
    # 测试发送预警邮件
    result = send_alert_email(
        alert_type="陌生人检测",
        location="前门",
        additional_info="系统检测到一名陌生人在门口停留超过30秒，行为可疑。"
    )
    
    if result:
        print("测试邮件发送成功!")
    else:
        print("测试邮件发送失败!")